import React, {useState} from "react";
import './index.scss'
import {Button, Image, Input, message} from "antd";
import PropTypes from "prop-types";
import {useHistory} from "react-router-dom/cjs/react-router-dom";
import useLoginByText from "../../hooks/useLoginByText";
import axios from "axios";
import defaultImg from '../../assets/images/register.png'

export default function LoginForm(props) {

  const [loginState, setLoginState] = useState('text')
  const codeSrc = props.src

  return (
    <div className="login">
      <div className="form-box">
        <div className="login-type">
          <div className="text-login" onClick={() => setLoginState('text')}>
            <span>账号密码登录</span>
          </div>
          <div className="code-login" onClick={() => setLoginState('code')}>
            <span>二维码登录</span>
          </div>
        </div>
        {loginState === 'text' ? <TextLogin/> : <CodeLogin src={codeSrc || ""}/>}
        <div className="login-footer">
          <span>其他登录方式</span>
        </div>
      </div>
    </div>
  )
}

function CodeLogin(props) {
  return (
    <div className="login-form">

      <div className="code-box">
        <Image
          src={props.src}
          fallback={defaultImg}
        />
      </div>

    </div>
  )
}

function TextLogin() {
  const history = useHistory()
  const {loginInfo, dispatch} = useLoginByText()

  const handleChange = (e) => {
    const {name, value} = e.target
    switch (name) {
      case 'username':
        dispatch({type: 'USERNAME', value})
        break
      case 'password':
        dispatch({type: 'PASSWD', value})
        break
      default:
        break
    }
  }
  const login = async () => {
    const params = new URLSearchParams()
    params.append('username', loginInfo.username)
    params.append('password', loginInfo.password)
    const res = await axios.post(`/fras/login`, params)
    if(res.data.code === 200) {
      message.success('登录成功', 1)
      window.sessionStorage.setItem('my_token', res.data.data.token)
      history.push('/main')
    }
    else {
      message.error(res.data.msg, 1)
    }
  }
  return (
    <div className="login-form">
      <div className="text-login-box">
        <p>账号登录</p>

        <Input placeholder="请输入账号" size="large" name="username" value={loginInfo.username} onChange={handleChange}/>
        <Input.Password placeholder="请输入密码" size="large" name="password" value={loginInfo.password}
                        onChange={handleChange}/>

        <Button className="login-btn" size="large" onClick={login}>登录</Button>
      </div>
      <div className="text-reg-box">
        <span>忘记密码?</span>
        <span onClick={()=>history.push('/register')}>新人注册!</span>
      </div>
    </div>
  )
}

CodeLogin.propTypes = {
  src: PropTypes.string.isRequired
}

LoginForm.propTypes = {
  state: PropTypes.oneOf(
    ['text', 'code']
  )
}